package com.blog.controller.frontpage;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.blog.controller.base.BaseServlet;
import com.blog.entity.UserEntity;
import com.blog.service.frontpage.UserService;
import com.blog.utils.TimeUtils;

@WebServlet("/reg")
public class RegServlet extends BaseServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		forward("llpfrontpage/reg");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");

		// 获得昵称
		String uname = req.getParameter("uname");
		// 获得昵称
		String phone = req.getParameter("phone");
		// 获得昵称
		String pwd = req.getParameter("pwd");
		// 获得页面输入的验证码
		String yzm = req.getParameter("yzm");

		// 定义一个集合保存错误信息
		HashMap<String, Object> ms = new HashMap<>();
		// 校验表单数据
		if (uname == null || uname.isEmpty()) {
			ms.put("error", "用户名不能为空！");
		}
		if (pwd == null || pwd.isEmpty()) {
			ms.put("error", "密码不能为空！");
		}
		if (yzm == null || yzm.isEmpty()) {
			ms.put("error", "验证码不能为空！");
		}
		if(phone == null || phone.isEmpty()) {
			ms.put("error", "手机号不能为空！");
		}
		
		// 获得生成图片的验证码
		Object checkcode_session = req.getSession().getAttribute("checkcode_session");
		// 进行验证码比对和生成文字是否一致
		if (!checkcode_session.equals(yzm)) {
			ms.put("error", "验证码不正确");
		}
		
		if(!ms.isEmpty()){			
			//重定向到登录页面
			redirect("reg", ms);
			return;
		}else {
			redirect("/login");
			Date date = new Date();
			TimeUtils timeUtil = new TimeUtils();
			java.sql.Date regtime = timeUtil.time(date);
			UserEntity user = new UserEntity();
			user.setUser_name(uname);
			user.setUser_phone(phone);
			user.setUser_password(pwd);
			user.setUser_ragtime(regtime);
			//向数据库插入一条用户信息
			UserService service = new UserService();
			service.insertUserForReg(user);
		}
		
		
		
	}

}
